import 'package:flutter/material.dart';
import 'dlna/dlna.dart';
import 'dart:async';
import 'device_control_page.dart';
import 'media_server_page.dart';

class DLNADevicePage extends StatefulWidget {
  const DLNADevicePage({super.key});

  @override
  _DLNADevicePageState createState() => _DLNADevicePageState();
}

class _DLNADevicePageState extends State<DLNADevicePage> {
  final DLNAManager _manager = DLNAManager();
  final List<dynamic> _devices = []; // 支持 DLNADevice 和 MediaServer
  StreamSubscription<Map<String, dynamic>>? _subscription;
  bool _isSearching = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _startSearch();
  }

  Future<void> _startSearch() async {
    setState(() {
      _isSearching = true;
      _errorMessage = null;
      _devices.clear();
    });

    try {
      final deviceManager = await _manager.start();
      _subscription?.cancel(); // 取消之前的订阅
      _subscription = deviceManager.devices.stream.listen(
            (deviceMap) {
          if (!mounted) return; // 防止在 widget 销毁后调用 setState
          setState(() {
            _devices.clear();
            _devices.addAll(deviceMap.values.where(
                  (device) => !device.info.friendlyName.contains('Wireless'),
            ));
            _isSearching = false;
          });
        },
        onError: (error) {
          setState(() {
            _isSearching = false;
            _errorMessage = '搜索 DLNA 设备失败: $error';
          });
        },
      );

      // 设置 30 秒后停止搜索
      Timer(const Duration(seconds: 30), () {
        if (mounted) {
          _manager.stop();
          _subscription?.cancel();
          setState(() {
            _isSearching = false;
          });
          print('DLNA search stopped.');
        }
      });
    } catch (e) {
      setState(() {
        _isSearching = false;
        _errorMessage = '启动 DLNA 搜索失败: $e';
      });
    }
  }

  @override
  void dispose() {
    _subscription?.cancel();
    _manager.stop();
    super.dispose();
  }

  String _getDeviceType(dynamic device) {
    try {
      if (device is DLNADevice) {
        return '媒体渲染器 (${device.info.deviceType})';
      } else if (device is MediaServer) {
        return '媒体服务器 (${device.info.deviceType})';
      }
      return '未知类型';
    } catch (e) {
      return '未知类型';
    }
  }

  IconData _getDeviceIcon(dynamic device) {
    if (device is DLNADevice) {
      return Icons.cast;
    } else if (device is MediaServer) {
      return Icons.storage;
    }
    return Icons.device_unknown;
  }

  void _navigateToDevicePage(BuildContext context, dynamic device) {
    if (device is DLNADevice) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => DeviceControlPage(device: device),
        ),
      );
    } else if (device is MediaServer) {
      final renderers = _devices.whereType<DLNADevice>().toList();
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => MediaServerPage(server: device, renderers: renderers),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('DLNA 设备列表'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _isSearching ? null : _startSearch,
            tooltip: '重新搜索设备',
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, color: Colors.red, size: 48),
            const SizedBox(height: 10),
            Text(
              _errorMessage!,
              style: const TextStyle(color: Colors.red),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _startSearch,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_isSearching && _devices.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 10),
            Text('正在搜索 DLNA 设备...'),
          ],
        ),
      );
    }

    if (_devices.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.devices, size: 48, color: Colors.grey),
            const SizedBox(height: 10),
            const Text('未发现 DLNA 设备'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _startSearch,
              child: const Text('重新搜索'),
            ),
          ],
        ),
      );
    }

    return ListView.separated(
      itemCount: _devices.length,
      separatorBuilder: (context, index) => const Divider(height: 1),
      itemBuilder: (context, index) {
        final device = _devices[index];
        return ListTile(
          leading: Icon(_getDeviceIcon(device)),
          title: Text(device.info.friendlyName),
          subtitle: Text(
            '${device.info.URLBase}\n类型: ${_getDeviceType(device)}',
          ),
          isThreeLine: true,
          onTap: () => _navigateToDevicePage(context, device),
        );
      },
    );
  }
}
